from pathlib import Path
from paddleocr import PaddleOCR, draw_ocr, download_with_progressbar
from PIL import Image
import os

BASE_DIR = Path(__file__).resolve().parent.parent
PROJECT_ROOT = os.path.join(BASE_DIR, 'pywebsite')
ORC_FONT_ROOT = os.path.join(PROJECT_ROOT, 'fonts')
ORC_MODEL_ROOT = os.path.join(PROJECT_ROOT, 'models')

DET_MODEL_DIR = os.path.join(ORC_MODEL_ROOT, 'ch_PP-OCRv3_det_infer')
REC_MODEL_DIR = os.path.join(ORC_MODEL_ROOT, 'ch_PP-OCRv3_rec_infer')


def get_ocr_result(filepath, det_model_dir=DET_MODEL_DIR, rec_model_dir=REC_MODEL_DIR):

    ocr = PaddleOCR(det_model_dir=det_model_dir, rec_model_dir=rec_model_dir, det_db_score_mode='slow',
                    use_angle_cls=True)
    # ocr = PaddleOCR(use_angle_cls=True,det_db_score_mode='slow')  # need to run only once to download and load model into memory //, lang="ch"
    result = ocr.ocr(filepath, cls=True)

    # img_path = 'http://n.sinaimg.cn/ent/transform/w630h933/20171222/o111-fypvuqf1838418.jpg'
    # result = ocr.ocr(img_path, cls=True)
    # download_with_progressbar(img_path, 'tmp.jpg')
    # image = Image.open('tmp.jpg').convert('RGB')
    return result


def get_ocr_result_img(image, boxes, txts, scores):
    im_show = draw_ocr(image, boxes, txts, scores, font_path=os.path.join(ORC_FONT_ROOT, '方正黑体简体.TTF'))
    im_show = Image.fromarray(im_show)
    return im_show


def get_ocr_result_by_url(url, det_model_dir=DET_MODEL_DIR, rec_model_dir=REC_MODEL_DIR):
    ocr = PaddleOCR(det_model_dir=det_model_dir, rec_model_dir=rec_model_dir, det_db_score_mode='slow',
                    use_angle_cls=True)
    # img_path = 'https://marisfrolg.obs.myhuaweicloud.com/POS/PRD/SaleBig/202301/202301011219101672575550539.jpg'
    result = ocr.ocr(url, cls=True)
    return result
